<template>
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px" class="form-container">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="goodsName">
            <el-input v-model="formData.goodsName" placeholder="请输入商品名称" clearable />
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price">
            <el-input-number v-model="formData.price" :precision="2" :min="0" controls-position="right"
                style="width: 100%" />
        </el-form-item>

        <!-- 商品状态 -->
        <el-form-item label="商品状态" prop="status">
            <el-select v-model="formData.status" style="width: 100%">
                <el-option :value="0" label="下架" />
                <el-option :value="1" label="在售" />
                <el-option :value="2" label="缺货" />
            </el-select>
        </el-form-item>

        <!-- 上架时间 -->
        <el-form-item label="上架时间" prop="createTime">
            <el-date-picker v-model="formData.createTime" type="date" placeholder="选择上架日期" value-format="yyyy-MM-dd"
                style="width: 100%" disabled />
        </el-form-item>

        <!-- 参考图片 -->
        <el-form-item label="商品图片" prop="image">
            <el-upload action="#" :auto-upload="false" :show-file-list="false" :on-change="handleImageChange"
                accept="image/*">
                <el-button size="small" type="primary">更换图片</el-button>
                <div class="el-upload__tip">建议上传 500x500 像素的JPG/PNG文件</div>
            </el-upload>
            <img v-if="formData.image" :src="formData.image" class="preview-image" alt="商品图片">
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
            <el-button type="primary" @click="submitForm">立即更新</el-button>
            <el-button @click="resetForm">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import { GetById, UPGoods } from '@/api/admin/Goods'
import request from '@/utils/request'
import dayjs from 'dayjs'

export default {
    data() {
        return {
            formData: {
                id: '',
                goodsName: '',
                price: null,
                status: 0,
                createTime: '',
                image: ''
            },
            rules: {
                goodsName: [
                    { required: true, message: '商品名称不能为空', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                    {
                        type: 'number',
                        validator: (rule, value, callback) => {
                            if (value >= 0) {
                                callback()
                            } else {
                                callback(new Error('价格不能为负数'))
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                status: [
                    { required: true, message: '请选择商品状态', trigger: 'change' }
                ],
                image: [
                    { required: true, message: '请上传商品图片', trigger: 'change' }
                ]
            }
        }
    },

    methods: {
        // 初始化商品数据
        async getGoods(goodsId) {
            try {
                const { data } = await GetById(goodsId)
                if (data) {
                    console.log(data);
                    this.formData = {
                        id: data.id,
                        goodsName: data.goodsName?.trim() || '',
                        price: Number(data.price) || 0,
                        status: Number(data.status) || 0,
                        createTime: data.createTime
                            ? dayjs(data.createTime).format('YYYY-MM-DD')
                            : dayjs().format('YYYY-MM-DD'),
                        image: data.image || ''
                    }
                }
            } catch (error) {
                console.error('商品加载失败:', error)
                this.$message.error('商品信息加载失败')
                this.$router.back()
            }
        },

        // 图片处理
        async handleImageChange(file) {
            try {
                // 生成临时预览
                const previewURL = URL.createObjectURL(file.raw)
                this.formData.image = previewURL

                // 上传到服务器
                const serverUrl = await this.uploadImage(file.raw)
                this.formData.image = serverUrl
            } catch (error) {
                console.error('图片上传失败:', error)
                this.$message.error('图片更新失败：' + (error.response?.data?.msg || '服务器错误'))
                this.formData.image = ''
            }
        },

        // 图片上传方法
        async uploadImage(file) {
            const formData = new FormData()
            formData.append('file', file)
            formData.append('goodsName', this.formData.goodsName)

            const { data } = await request.post('/common/upload', formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            })

            if (!data?.data) {
                throw new Error('未获取到有效图片地址')
            }
            return data.data
        },

        // 表单提交
        async submitForm() {
            try {
                const valid = await this.$refs.formRef.validate()
                if (!valid) return
                const payload = {
                    id: this.formData.id,
                    goodsName: this.formData.goodsName,
                    price: this.formData.price,
                    status: this.formData.status,
                    image: this.formData.image,
                    createTime: dayjs(this.formData.createTime).valueOf()
                }
                const { data } = await UPGoods(payload)
                if (data.code === 200) {
                    this.$message.success('商品更新成功')
                    setTimeout(() => {
                        this.$router.push('/home/Goods')
                    }, 1500)
                } else {
                    this.$message.error(data.msg || '更新失败')
                }
            } catch (error) {
                console.error('更新失败:', error)
                this.$message.error('商品更新失败: ' + (error.response?.data?.msg || '服务器错误'))
            }
        },

        // 重置表单
        resetForm() {
            this.$refs.formRef.resetFields()
            this.getGoods(this.formData.id)
        }
    },

    mounted() {
        const goodsId = this.$route.params.goodsId
        if (goodsId) {
            this.getGoods(goodsId)
        } else {
            this.$message.error('无效的商品ID')
            this.$router.back()
        }
    }
}
</script>

<style scoped>
.form-container {
    width: 800px;
    margin: 20px auto;
    padding: 30px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.preview-image {
    display: block;
    margin-top: 10px;
    max-width: 200px;
    max-height: 200px;
    border: 1px solid #eee;
    border-radius: 4px;
    padding: 5px;
}

.el-upload__tip {
    color: #999;
    font-size: 12px;
    margin-top: 5px;
}

.el-form-item {
    margin-bottom: 22px;
}

:deep(.el-input-number .el-input__inner) {
    text-align: left;
}
</style>